package com.app.couponsharelife.ui.main.home.local

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.ui.viewmodel.LocalViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_local_shop_pay.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit

class LocalShopPayActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_local_shop_pay

    private var mViewModel: LocalViewModel? = null

    private var shopId = ""

    private var shopName = ""

    private var mobile = ""

    private var isReduceMoney = false

    private var totalMoney = ""

    private var disposable: Disposable? = null

    private var count = 0L

    override fun initViews() {
        if (intent.getStringExtra("shopId") != null)
            shopId = intent.getStringExtra("shopId")
        else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        if (intent.getStringExtra("mobile") != null)
            mobile = intent.getStringExtra("mobile")
        else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        if (intent.getStringExtra("shopName") != null)
            shopName = intent.getStringExtra("shopName")
        else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        tvLocalShopName.text = "正在付款给 $shopName"
        tvPay.setOnClickListener {
            if (totalMoney == "") {
                showToastMsg("付款金额不正确")
                return@setOnClickListener
            }
//            val intent = Intent(this, LocalShopPayResultActivity::class.java)
//            intent.putExtra("mobile", mobile)
//            intent.putExtra("shopName", shopName)
//            intent.putExtra("money", totalMoney)
//            intent.putExtra("status", true)
//            startActivity(intent)
            showToastMsg("该商户暂未激活！")
        }
        ivInputMoney.setOnClickListener {
            isReduceMoney = !isReduceMoney
            if (isReduceMoney) {
                etReduceMoney.visibility = View.VISIBLE
                ivInputMoney.setImageResource(R.drawable.ic_local_shop_pay_select)
            } else {
                etReduceMoney.visibility = View.GONE
                ivInputMoney.setImageResource(R.drawable.ic_local_shop_pay_no_select)
            }
        }
        initToolBar()
        initEditText()
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "支付"
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)
        if (!mViewModel!!.payMoneyCalculate()!!.hasObservers()) {
            mViewModel!!.payMoneyCalculate()!!.observe(this, Observer {
                if (it == null) {
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshPayMoneyCalculate(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshPayMoneyCalculate(hashMapOf(), false)
                        showToastMsg("暂无数据")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshPayMoneyCalculate(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            tvPayMoneyTitle.visibility = View.VISIBLE
                            tvPayMoneyLogo.visibility = View.VISIBLE
                            tvPayMoney.visibility = View.VISIBLE
                            tvPayMoney.text = it.data.data!!.payPrice
                            totalMoney = it.data.data!!.payPrice
                            if (it.data.data!!.cartTitle != null &&
                                    it.data.data!!.cardPrice != null &&
                                    it.data.data!!.cardType != null) {
                                ivDiscountCoupon.visibility = View.VISIBLE
                                tvDiscountCoupon.visibility = View.VISIBLE
                                tvDiscountCoupon.text = it.data.data!!.cartTitle
                                tvDiscountCouponMoney.visibility = View.VISIBLE
                                tvDiscountCoupon.text = "－¥${it.data.data!!.cardPrice}"
                            }
                        } else {
                            showToastMsg("计算失败")
                        }
                    }
                }
            })
        }
    }

    private fun initEditText() {
        etTotalMoney.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                count = 0L
                if (disposable == null) {
                    disposable = Observable.interval(0, 500, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                count++
                                println(count)
                                if (count == 2L) {
                                    payMoneyCalculate()
                                }
                            }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        etReduceMoney.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (isReduceMoney) {
                    count = 0L
                    if (disposable == null) {
                        disposable = Observable.interval(0, 500, TimeUnit.MILLISECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe {
                                    count++
                                    if (count == 2L) {
                                        payMoneyCalculate()
                                    }
                                }
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    private fun payMoneyCalculate() {
        if (TextUtils.isEmpty(etTotalMoney.text)) {
            showToastMsg("请输入消费总额")
            return
        }
        val map = HashMap<String, String>()
        map["mobile"] = mobile
        map["shopId"] = shopId
        map["amount"] = etTotalMoney.text.toString().trim()
        if (isReduceMoney)
            map["noDiscount"] = etReduceMoney.text.toString().trim()
        else
            map["noDiscount"] = "0"
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshPayMoneyCalculate(map, true)
    }

    override fun onDestroy() {
        if (disposable != null && !disposable!!.isDisposed) {
            disposable!!.dispose()
            disposable = null
        }
        super.onDestroy()
    }
}
